var _gl = require('opengl');
var _MeshNode = require('drawable/meshnode.js');
var _inherit = require('core/inherit.js');
var _createMesh = require('glcore/meshbuffer.js').createMesh;
var _Filler = require('drawable/framefiller.js');
var _Buffer = require('glcore/buffer.js').Buffer;

function Progress(material, frame) {
    _MeshNode.call(this, _createMesh('p3t2', 7, _gl.TRIANGLE_FAN), material);

    var structure = this.mBuffer.adapter();
    this.mFiller = _Filler.createFiller(structure, frame);
    this.mWhole = new _Buffer({
        stride: structure.byteLength,
        count: 7,
        type: Int8Array,
        normalize: false
    });
    this.setup(frame.width(), frame.height());
    this.mFiller.setBuffer(this.mBuffer);

    this.setPercent(0);
}
_inherit(Progress, _MeshNode);
Progress.prototype.setup = function (w, h) {
    this.setSize(w, h);

    var c = w / 2;
    var f = this.mFiller;
    f.setBuffer(this.mWhole);
    f.seek(0);
    f.appendPoint(c, c);// 0 center
    f.appendPoint(c, h);// 1 bottom center
    f.appendPoint(0, h);// 2 left bottom
    f.appendPoint(0, 0);// 3 left head
    f.appendPoint(w, 0);// 4 right head
    f.appendPoint(w, h);// 5 right bottom
    f.appendCopy(1);
};
Progress.prototype.setPercent = function (p) {
    if (p <= 0) {
        this.mVisiable = false;
    } else {
        this.mVisiable = true;
        if (p >= 1) {
            this.mFiller.copyBuffer(this.mWhole, 0, this.mBuffer, 0, 7);
            this.mBuffer.setPoint(7);
        } else {
            var c = this.getSize()[0] / 2;
            var cp = 3;
            var x, y;

            if (p < 0.25) {
                cp = 3;
                x = 0;
                y = c - c * Math.tan(p * Math.PI);
            } else if (p < 0.75) {
                cp = 4;
                x = c + c * Math.tan((p - 0.5) * Math.PI);
                y = 0;
            } else {
                cp = 5;
                x = c * 2;
                y = c + c * Math.tan(p * Math.PI);
            }

            var f = this.mFiller;
            f.copyBuffer(this.mWhole, 0, this.mBuffer, 0, cp);
            f.seek(cp);
            f.appendPoint(x, y);
            this.mBuffer.setPoint(cp + 1);
        }

        this.mBuffer.upload();
    }
};
Progress.prototype.upload = function () {
    this.mBuffer.upload();
};

module.exports = Progress;